#!/usr/bin/env python
#coding:utf-8
# Author:  G --<KnownSec>
# Purpose: 域名纠错服务器识别
# Created: 2010/11/29

import sys
import unittest
import socket,_socket
import struct


########################################################################
class BrokenDomain(object):
	""""""

	#----------------------------------------------------------------------
	def __init__(self):
		"""Constructor"""
		self.sp_ips = {
		    'chinaunicom':{
		        #北京
		        'beijing':
		        self.build_ips('202.106.199.34-202.106.199.40',unpack=True)
		        +
		        ['211.98.70.194']
		        +
		        self.build_ips('220.250.64.18-220.250.64.26',unpack=True),
		        #山东
		        'shandong':self.build_ips('123.129.254.11-123.129.254.19',unpack=True),
		        #河北
		        'hebei':self.build_ips('221.192.153.41-221.192.153.46',unpack=True),
		        #河南
		        'henan':self.build_ips('202.111.148.132-202.111.148.138',unpack=True),
		        #山西
		        'shanxi':self.build_ips('221.204.244.36-221.204.244.41',unpack=True),
		        #黑龙江
		        'heilongjiang':self.build_ips('125.211.213.130-125.211.213.134',unpack=True),
		        #吉林
		        'jilin':self.build_ips('202.98.24.121-202.98.24.125',unpack=True),
		        #辽宁
		        'liaoning':self.build_ips('60.19.29.21-60.19.29.25',unpack=True),
		        #内蒙古
		        'neimenggo':self.build_ips('202.99.254.230-202.99.254.233',unpack=True),
		        #天津
		        'tianjing':self.build_ips('218.68.250.117-218.68.250.121',unpack=True),
		        },

		    'ct10000':{
		        #广东
		        'guangdong':['113.108.180.57'],		
		        #未知
		        'unknown':
		        ['75.125.148.76']
		        +
		        ['115.47.73.89']
		    }

		}




	#----------------------------------------------------------------------
	def get_ip(self,domain):
		""""""
		try:
			ip = socket.gethostbyname(domain)
			return ip
		except:
			return False



	#----------------------------------------------------------------------		
	def build_ips(self,ips,unpack=False):
		"""
		输入格式：
		ips ==> 10.10.10.1-10.10.10.255                           最大不超过c类地址做范围，也就是不超过1-255
		    ==> 10.10.10.1                                        一个地址
			==> 10.10.10.1,10.10.10.3-10.10.10.10                 多个区间以逗号间隔
			==> 10.10.10.1-10.10.10.255\n10.10.11.1-10.10.11.255  以一行一个作为ip列表，这里定义了2个c段
		输出格式：
		ips ==> [(10.10.10.1,10.10.10.2,...,10.10.10.255)]        以列表作为集合，一个元组为一次任务集合
		    ==> [(10.10.10.1,)]
			==> [(10.10.10.1,10.10.10.3,10.10.10.4,...,10.10.10.10)]
			==> [(10.10.10.1,...,10.10.10.255),(10.10.11.1,...,10.10.11.255)] 一个任务存放一个元组，每个元组都是同一个c段
		"""
		result_ips = []
		ip_list = ips.split('\n') #切割多行为多个任务

		for ip_part in ip_list:

			if ',' in ip_part:
				ip_ranges = ip_part.split(',')
			else:
				ip_ranges = [ip_part]
			part_list = set()
			for ip_range in ip_ranges:
				if '-' in ip_range:
					start,end = ip_range.split('-')
					start = self.ip_to_int(start)
					end = self.ip_to_int(end)
					for ip in range(start,end+1):
						part_list.add(self.int_to_ip(ip))
				else:
					part_list.add(ip_range)
			result_ips.append(tuple(part_list))
		if unpack:
			unpack_ips = []
			for c in result_ips:
				for ip in c:
					unpack_ips.append(ip)
			return unpack_ips
		return result_ips

	#----------------------------------------------------------------------
	def ip_to_int(self,ip):
		'''获取IP的十进制的值 用来存储'''
	
		try:
			# >L 为了32位和64位兼容 said by cos
			return struct.unpack('>L', _socket.inet_aton(ip))[0]  
		except Exception,e:
			print e
			return 0
		
	#----------------------------------------------------------------------
	def int_to_ip(self,ip):
		'''获取IP的正常地址 用来显示'''
	
		try:
			if ip:
				# >L 为了32位和64位兼容 said by cos
				return _socket.inet_ntoa(struct.pack('>L', ip))  
		except:
			pass
		return ''

if __name__=='__main__':
	
	bd = BrokenDomain()
	i = bd.ip_to_int('10.10.10.10')
	print bd.int_to_ip(i)
	ip = bd.get_ip('www.knownsecinmaldbtest.com')
	print ip
	if ip:
		for sp,provinces_ips in bd.sp_ips.items():
			for province,ips in provinces_ips.items():
				if ip in ips:
					print ip